package com.itbaizhan;

import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class MongodbCrud {

    public static void main(String[] args) {

        try {

            MongoClient mongoClient = getMongoClient("config.properties");
            //获取database对象
            MongoDatabase mydb = mongoClient.getDatabase("mydb");
            //创建集合
           // mydb.createCollection("exampleCollection2");
            //获取集合对象
            MongoCollection<Document> collection = mydb.getCollection("exampleCollection2");

            //创建文档
          //  Document document = Document.parse("{name:'wang',city:'bei',birthday:new ISODate('2001-08-02'),experctSalary: 13000}");
           // Document document2 = Document.parse("{name:'meng',city:'bei',birthday:new ISODate('2001-08-02'),experctSalary: 15000}");
            //把方档放进集合
           // collection.insertOne(document);
          //  collection.insertOne(document2);

            /*文档查询*/
            Document sdoc = new Document();
            //倒序查询
            sdoc.append("experctSalary",-1);
            FindIterable<Document> findIterable = collection.find().sort(sdoc);
//            for(Document document1 :findIterable){
//                System.out.println(document1);
//            }


            //按指定属性查询
//            FindIterable<Document> documents = collection.find(new Document("experctSalary", new Document("$eq", 13000)));
//            for (Document document: documents){
//                System.out.println(document);
//            }

            //过滤查询  过滤完成后，按照指定的排序条件进行排序   gt :大于    lt: 小于  lte: 小于且等于  eq ；等于
            FindIterable<Document> documents = collection.find(Filters.gt("experctSalary", 12000)).sort(sdoc);
            for (Document document : documents){
                System.out.println(document);
            }


            //关闭
            mongoClient.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //获取MongoClient
    private static MongoClient getMongoClient(String propertyFileName) throws IOException {
        Properties properties = new Properties();
        //使用classloader 加载properties 文件获取对应的输入流
        InputStream in = MongodbExample2.class.getClassLoader().getResourceAsStream(propertyFileName);
        //使用properties加载输入流
        properties.load(in);
        //获取key的value
        String connectionString = properties.getProperty("mongodb.uri");

        //获取mongoClient 对象
        return MongoClients.create(connectionString);
    }
}
